﻿using Atlanchim.Crm.Mui.Commands;
using Atlanchim.Crm.Mui.Helpers;
using FirstFloor.ModernUI.Windows.Controls;
using Lmondeil.Crm.EF;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;

namespace Atlanchim.Crm.Mui.Pages.Adresses
{
    public class PageViewAdresseModel : AbstractPageViewModel
    {
        /// <summary>
        /// Contact de référence
        /// </summary>
        public Adresse Adresse { get; set; }

        /// <summary>
        /// Url d'accès à la page d'édition
        /// </summary>
        public override string EditUrl { get; set; }

        /// <summary>
        /// Chargement
        /// </summary>
        public override void Load()
        {
            // Lecture du fragment
            int idAdresse = 0;
            int.TryParse(this.DicFragments["IdAdresse"], out idAdresse);

            // Chargement
            using (CrmContext context = new CrmContext())
            {
                // Contact
                this.Adresse = context
                                .Adresses
                                .Where(adresse => adresse.Id == idAdresse)
                                .FirstOrDefault();
                this.EditUrl = string.Format("/Pages/Adresses/PageEditAdresse.xaml#IdAdresse={0}", idAdresse);
            }

            // Notification
            OnPropertyChanged("Adresse");
        }

        /// <summary>
        /// Suppression
        /// </summary>
        protected override void OnDeleteCurrentEntity()
        {
            using (CrmContext context = new CrmContext())
            {
                try
                {
                    context.Adresses.Attach(Adresse);
                    context.Adresses.Remove(Adresse);
                    context.SaveChanges();
                }
                catch (DbEntityValidationException deleteEntityException)
                {
                    string message = PersistenceErrorHelper.GetEntityValidationErrorMessages(deleteEntityException);
                    ModernDialog.ShowMessage(message, "Erreur", System.Windows.MessageBoxButton.OK);
                }
                catch (Exception deleteException)
                {
                    string message = "Une erreur technique est survenue : " + deleteException.Message;
                    ModernDialog.ShowMessage(message, "Erreur", System.Windows.MessageBoxButton.OK);
                }
            }
        }
    }
}
